console.log('for webpack5.x')
const fs = require('fs')
module.exports = class clearSetting {
    constructor(options){
        console.log(options)
        this.options = options
    }
    apply(compiler) {
        compiler.hooks.emit.tapAsync('clearSetting', (compilation,callback) => {
            const { file,toClear,version } = this.options
            let body = JSON.stringify(fs.readFileSync(file,'utf-8'));
            let reg = new RegExp(`${toClear}.*?\;`,"g")
            let to = `${toClear} = ${"'"+"'"};`
            if(version) {
                // body.replace('})(window)',`SITE_CONFIG.version='${version}' })(window)`);
                let idx = body.indexOf('})')
                console.log(idx)
                body = body.substring(0,idx) + `SITE_CONFIG.version='${version}';` + body.substring(idx)
            }
            body = body.replace(reg,to)
            fs.writeFileSync('./dist/static/config/setting.js',JSON.parse(body))
            compilation.assets[file.slice(1)] = {
                source: function(){
                    return JSON.parse(body)
                },
                size: function(){
                    return body.length
                }
            }
            callback()
        })
    }
}